package cn.ssm.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ssm.pojo.Admin;
import cn.ssm.service.AdminService;
import cn.ssm.util.Constans;
import cn.ssm.util.Constans2;

/**
 * 登录控制器
 * 
 * @author lenovo
 *
 */
@Controller
public class LoginController {
	@Autowired
	AdminService adminService;
	
	/**
	 * 获取登录的用户信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getLoginAdmin.htm")
	@ResponseBody
	public Object getLoginAdmin(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		
		try {
			Admin admin = (Admin) request.getSession().getAttribute(Constans.LOGIN_KEY);
			
			map.put("result", admin);
			map.put("message", "获取登录用户成功");
			map.put("success", true);
			
		} catch (Exception e) {
			map.put("message", "获取登录用户出现异常");
		}
		return map;
	}

	/**
	 * 用户登录
	 * @param adminCode
	 * @param adminPassword
	 * @param request
	 * @return
	 */
	@RequestMapping("/login.htm")
	@ResponseBody
	public Object login(@Param("adminCode") String adminCode, @Param("adminPassword") String adminPassword,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		try {
			Admin admin = adminService.getAdmin(adminCode, adminPassword);
			if(admin != null){
				request.getSession().setAttribute(Constans.LOGIN_KEY, admin);
				
				map.put("success", true);
				map.put("message", "存在此用户");
			}else{
				map.put("success", false);
				map.put("message", "用户不存在！");
			}
		} catch (Exception e) {
			map.put("message", "查询用户出错，请联系管理员");
			e.printStackTrace();
		}
		return map;
	}
	
	
	@RequestMapping("/adminOut.htm")
	@ResponseBody
	public Object userOut(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		request.getSession().setAttribute(Constans.LOGIN_KEY, null);
		if (request.getSession().getAttribute(Constans.LOGIN_KEY) == null) {
			map.put("message", "登出成功");
			map.put("success", true);
		}
		return map;
	}
}
